﻿using Mark.Data;
using Microsoft.EntityFrameworkCore;
using Mark.Services;

namespace Mark
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
        }

        protected override Window CreateWindow(IActivationState? activationState)
        {
            var window = new Window(new AppShell())
            {
                Height = 760,
                Width = 900,
                MinimumHeight = 700,
                MinimumWidth = 850,
            };

            // 居中显示窗口
            var displayInfo = DeviceDisplay.Current.MainDisplayInfo;
            var screenWidth = displayInfo.Width / displayInfo.Density;
            var screenHeight = displayInfo.Height / displayInfo.Density;
            
            window.X = (screenWidth - window.Width) / 2;
            window.Y = (screenHeight - window.Height) / 2;

            // 初始化数据库
            _ = Task.Run(async () => await InitializeDatabaseAsync());

            return window;
        }

        private async Task InitializeDatabaseAsync()
        {
            try
            {
                // 直接创建DbContext进行数据库初始化
                var optionsBuilder = new DbContextOptionsBuilder<MarkDbContext>();
                var dbPath = Path.Combine(FileSystem.AppDataDirectory, "mark.db");
                optionsBuilder.UseSqlite($"Data Source={dbPath}");

                using var context = new MarkDbContext(optionsBuilder.Options);
                
                // 应用迁移
                await context.Database.MigrateAsync();
                
                // 使用DatabaseInitializer进行数据预制
                var logger = new SimpleLogger();
                var dbInitializer = new DatabaseInitializer(context, logger);
                await dbInitializer.InitializeAsync();
                
                System.Diagnostics.Debug.WriteLine("数据库初始化完成");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"数据库初始化失败: {ex.Message}");
            }
        }
    }

    // 简单的日志记录器实现
    public class SimpleLogger : Microsoft.Extensions.Logging.ILogger<DatabaseInitializer>
    {
        public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
        public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true;
        public void Log<TState>(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
        {
            System.Diagnostics.Debug.WriteLine($"[{logLevel}] {formatter(state, exception)}");
        }
    }
}
